import { Tag, Space, Notification } from "@douyinfe/semi-ui";
import swr from "../utils/swr";
import Page from "../utils/page";
import {
  Table,
  Text,
  Loading,
  Button,
  Card,
  Input,
  Grid,
} from "@nextui-org/react";
import { IconEdit, IconExternalOpen, IconDelete } from "@douyinfe/semi-icons";
import { useState } from "react";
import EditExam from "../utils/edit-exam";
import { useRouter } from "next/router";
import DeleteConfirmation from "../utils/delete-confirmation";
import { BASEURL } from "../utils/config";
import { mutate } from "swr";

export default function Home() {
  const [editDialogVisiable, setEditDialogVisiable] = useState(false);
  const [editDialogData, setEditDialogData] = useState({});
  const [deleteDialogVisiable, setDeleteDialogVisiable] = useState(false);
  const [deleteDialogData, setDeleteDialogData] = useState({});
  const [newDialogData, setNewDialogData] = useState({});
  const router = useRouter();

  const { data, isLoading, isError } = swr("/exams/metadata");
  if (
    isLoading ||
    typeof data === "undefined" ||
    typeof data.detail !== "undefined"
  ) {
    return (
      <Page page="/exams">
        <Loading />
      </Page>
    );
  } else if (isError) {
    return (
      <Page page="/exams">
        <Text>获取考试列表失败</Text>
      </Page>
    );
  }
  const columns = [
    {
      label: "届次",
      key: "year",
    },
    {
      label: "名称",
      key: "name",
    },
    {
      label: "日期",
      key: "time",
    },
    {
      label: "状态",
      key: "status",
    },
    {
      label: "科目",
      key: "subjects",
    },
    {
      label: "操作",
      key: "operates",
    },
  ];
  let rows = [];
  let key = 1;
  for (let year in data) {
    for (let name in data[year]) {
      rows.push({
        key: key++,
        year: year,
        name: name,
        time: data[year][name].time,
        status: data[year][name].status,
        subjects: (
          <Space>
            {data[year][name].subjects.map((subject) => (
              <Tag size="large" key={subject}>
                {subject}
              </Tag>
            ))}
          </Space>
        ),
        operates: (
          <Space>
            <IconExternalOpen
              size="large"
              onClick={() => {
                router.push(`/exams/${year}/${name}`);
              }}
            />
            <IconEdit
              size="large"
              onClick={() => {
                setEditDialogVisiable(true);
                setEditDialogData({
                  year: year,
                  name: name,
                  time: data[year][name].time,
                  status: data[year][name].status,
                  subjects: data[year][name].subjects,
                });
              }}
            />
            <IconDelete
              size="large"
              onClick={() => {
                setDeleteDialogVisiable(true);
                setDeleteDialogData({
                  year: year,
                  name: name,
                });
              }}
            />
          </Space>
        ),
      });
    }
  }
  return (
    <Page page="/exams">
      <div
        style={{
          margin: "1rem",
        }}
      >
        <Card css={{ marginBottom: 15 }}>
          <Grid.Container gap={2}>
            <Grid xs={3}>
              <Input
                color="primary"
                size="lg"
                aria-labelledby="届次"
                placeholder="届次"
                type="number"
                initialValue={newDialogData.year}
                onChange={(e) => {
                  setNewDialogData({
                    ...newDialogData,
                    year: e.target.value,
                  });
                }}
              />
            </Grid>
            <Grid xs={3}>
              <Input
                color="primary"
                size="lg"
                aria-labelledby="考试名称"
                placeholder="考试名称"
                type="text"
                initialValue={newDialogData.name}
                onChange={(e) => {
                  setNewDialogData({
                    ...newDialogData,
                    name: e.target.value,
                  });
                }}
              />
            </Grid>
            <Grid xs={3}>
              <Input
                color="primary"
                size="lg"
                aria-labelledby="考试日期"
                placeholder="考试日期"
                type="date"
                initialValue={newDialogData.time}
                onChange={(e) => {
                  let date = new Date(e.target.value);
                  let dateStr = date.getFullYear() + "-";
                  dateStr += date.getMonth() + 1 < 10 ? "0" : "";
                  dateStr += date.getMonth() + 1 + "-";
                  dateStr += date.getDate() < 10 ? "0" : "";
                  dateStr += date.getDate();
                  setNewDialogData({
                    ...newDialogData,
                    time: e.target.value,
                  });
                }}
              />
            </Grid>
            <Grid xs={3}>
              <Button
                auto
                css={{ maxW: 100 }}
                onClick={() => {
                  if (
                    newDialogData.year &&
                    newDialogData.name &&
                    newDialogData.time
                  ) {
                    fetch(`${BASEURL}/exams/${newDialogData.year}`, {
                      method: "POST",
                      headers: {
                        Authorization: `Bearer ${localStorage.getItem(
                          "token"
                        )}`,
                      },
                    }).then(() => {
                      fetch(
                        `${BASEURL}/exams/${newDialogData.year}/${newDialogData.name}`,
                        {
                          method: "POST",
                          headers: {
                            "Content-Type": "application/json",
                            Authorization: `Bearer ${localStorage.getItem(
                              "token"
                            )}`,
                          },
                          body: JSON.stringify({
                            time: newDialogData.time,
                            status: "已归档",
                            subjects: {},
                          }),
                        }
                      )
                        .then((res) => res.json())
                        .then((res) => {
                          if (typeof res.detail === "undefined") {
                            Notification.success({
                              content: "添加成功",
                            });
                          } else {
                            Notification.error({
                              content: res.detail,
                            });
                          }
                          mutate(`${BASEURL}/exams/metadata`);
                        });
                    });
                  } else {
                    Notification.error({
                      content: "请填写完整信息",
                    });
                  }
                }}
              >
                添加考试
              </Button>
            </Grid>
          </Grid.Container>
        </Card>
        <Table
          aria-label="考试列表"
          css={{
            height: "auto",
            minWidth: "100%",
          }}
        >
          <Table.Header columns={columns}>
            {(column) => (
              <Table.Column key={column.key}>{column.label}</Table.Column>
            )}
          </Table.Header>
          <Table.Body items={rows}>
            {(item) => (
              <Table.Row key={item.key}>
                {(columnKey) => <Table.Cell>{item[columnKey]}</Table.Cell>}
              </Table.Row>
            )}
          </Table.Body>
        </Table>
        <EditExam
          editDialogVisiable={editDialogVisiable}
          setEditDialogVisiable={setEditDialogVisiable}
          editDialogData={editDialogData}
          setEditDialogData={setEditDialogData}
        />
        <DeleteConfirmation
          deleteDialogVisiable={deleteDialogVisiable}
          setDeleteDialogVisiable={setDeleteDialogVisiable}
          callback={() => {
            fetch(
              `${BASEURL}/exams/${deleteDialogData.year}/${deleteDialogData.name}`,
              {
                method: "DELETE",
                headers: {
                  Authorization: `Bearer ${localStorage.getItem("token")}`,
                },
              }
            )
              .then((res) => {
                return res.status === 204 ? Promise.resolve({}) : res.json();
              })
              .then((res) => {
                if (typeof res.detail === "undefined") {
                  Notification.success({
                    content: `删除成功`,
                  });
                } else {
                  Notification.error({
                    content: `删除失败 ${res.detail.msg}`,
                  });
                }
                mutate(`${BASEURL}/exams/metadata`);
              })
              .catch((err) => {
                Notification.error({
                  content: `删除失败 ${err}`,
                });
              });
            setDeleteDialogVisiable(false);
          }}
        >
          <Text size={18}>
            正在删除 {deleteDialogData.year} 年的 {deleteDialogData.name}
          </Text>
        </DeleteConfirmation>
      </div>
    </Page>
  );
}
